package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
	"time"
)

func chkError(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

func handleClient(conn net.Conn, ch chan int) {
	conn.Write([]byte("connect success...\n"))

	conn.SetReadDeadline(time.Now().Add(time.Minute))
	defer conn.Close()

	for {
		inputReader := bufio.NewReader(conn)
		input, err := inputReader.ReadString('\n')
		if err != nil {
			fmt.Println(err)
			break
		}
		cmd := strings.TrimSpace(input)
		if len(cmd) == 0 {
			continue
		}
		fmt.Println("客户端输入:"+cmd)
		//发送给客户端数据
		rep := "";
		rep += "server: "
		switch cmd {
		case "off":
			ch <- 1
			conn.Write([]byte(rep + "server will be off\n"))
			fmt.Println("no see")
			conn.Close()
		case "bye":
			conn.Write([]byte(rep + "see you\n"))
			fmt.Println("TA走了")
			conn.Close()
		case "time":
			rep += time.Now().Format("2006-01-02 15:04:05") +"\n"
			conn.Write([]byte(rep))
		default:
			rep += cmd + "\n"
			conn.Write([]byte(rep))
		}
		fmt.Println(rep)
	}
}

func main() {
	port := "127.0.0.1:1234"
	tcpaddr, err := net.ResolveTCPAddr("tcp4", port)
	chkError(err)
	fmt.Println("服务启动,监听"+port)
	tcplisten, err2 := net.ListenTCP("tcp", tcpaddr)
	chkError(err2)

	ch := make(chan int)
	for {
		conn, err3 := tcplisten.Accept()
		if err3 != nil {
			continue
		}

		go handleClient(conn, ch)

		if <-ch > 0 {
			fmt.Println("客户端要求关闭服务")
			os.Exit(0)
		}
	}
}